﻿using Dapper;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using OMG.Fill.Mulberry.Model;
using OMG.Fill.Mulberry.Model.Ent;
using ProjectShare;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace OMG.Fill.Mulberry.Service
{
    /// <summary>
    /// 表5蚕种生产情况统计表T_MulEggsProducStatist通用操作类
    /// </summary>
    public class MulEggsProducStatistServices : MulEggsProducStatists
    {
        DictServices dict = new DictServices();
        public Pager<List<MulEggsProducStatistEntity>> GetPageList(MulEggsProducStatistQuery query)
        {
            Pager<List<MulEggsProducStatistEntity>> obj = new Pager<List<MulEggsProducStatistEntity>>();
            var paramlist = new DynamicParameters();
            string strWhereSql = "";//from 表在下面，需完善其他查询条件在这里接的写，格式为："and xxx=@xxx空格,如下注释部分代码所示："
            //if (!string.IsNullOrEmpty(query.GroupCode))
            //{
            //  strWhereSql += "and GroupCode = @GroupCode ";
            //  paramlist.Add("GroupCode", query.GroupCode);
            //}
            string strFromSql = "from dbo.T_MulEggsProducStatist where 1=1 " + strWhereSql;
            string strTotal = "select count(1)" + strFromSql + strWhereSql;
            string strOrderSql = "";//自定义完成order by语句
            string strSql = @"select * from (select *,ROW_NUMBER() over (order by Id ) as RowNumber " + strFromSql + ") as t ";
            strSql += "where t.RowNumber between  @minRow and @maxRow" + strOrderSql;
            paramlist.Add("minRow", query.MinRow);
            paramlist.Add("maxRow", query.MaxRow);
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    obj.rows = dbCon.Query<MulEggsProducStatistEntity>(strSql, paramlist).ToList();
                    obj.total = dbCon.Query<int>(strTotal, paramlist).FirstOrDefault();
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "获取成功！";
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("获取表5蚕种生产情况统计表T_MulEggsProducStatist分页列表失败", ex);
                return obj;
            }
        }
        /// <summary>
        /// 获取指定对象
        /// </summary>
        public ResResult<List<MulEggsProducStatistEntity>> GetList(string ReportId)
        {
            ResResult<List<MulEggsProducStatistEntity>> obj = new ResResult<List<MulEggsProducStatistEntity>>();
            MulEggsProducStatistEntity model = new MulEggsProducStatistEntity();
            if (CheckRepCount(ReportId))
            {
                model.ReportId = ReportId;
                if (AddInfo(model).status > 0)
                {
                    obj.model = new List<MulEggsProducStatistEntity>();
                    obj.model.Add(model);
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "获取成功！";
                }
            }
            else
            {
                string strSql = @"select * from dbo.T_MulEggsProducStatist where ReportId = @ReportId";
                try
                {
                    using (var dbCon = ConnectFactory.GetOpenConnection())
                    {
                        obj.model = dbCon.Query<MulEggsProducStatistEntity>(strSql, new { ReportId = ReportId }).ToList();
                        obj.status = DefaultKey.SuccessResult;
                        obj.message = "获取成功！";
                        dbCon.Dispose();//数据库连接释放
                    }
                }
                catch (Exception ex)
                {
                    obj.status = DefaultKey.ErrorResult;
                    obj.message = ex.ToString().Trim();
                    LogHelper.ErrorLog("获取表1桑园面积统计表T_MulEggsProducStatist对象信息失败", ex);

                }
            }
            return obj;
        }
        /// <summary>
        /// 判定是否生成过报表
        /// </summary>
        /// <param name="reportId"></param>
        /// <returns>没生成过true,否则false</returns>
        public bool CheckRepCount(string reportId)
        {
            string strSql = @"select count(1) from dbo.T_MulEggsProducStatist where ReportId=@ReportId";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    //为0，没生成过true,否则false
                    return dbCon.Query<int>(strSql, new { ReportId = reportId }).FirstOrDefault() == 0 ? true : false;
                }
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLog("判断是否生成过表1桑园面积统计表T_MulEggsProducStatist失败", ex);
                return false;
            }
        }
        public ResResult<int> AddInfo(List<MulEggsProducStatistEntity> list)
        {
            ResResult<int> obj = new ResResult<int>();
            string strSql = @"INSERT INTO dbo.T_MulEggsProducStatist";
            strSql += "(";
            strSql += "Id,";
            strSql += "ReportId,";
            strSql += "SeedUnitName,";
            strSql += "Varieties,";
            strSql += "SeedProducSpring,";
            strSql += "SeedProducSummer,";
            strSql += "SeedProducAutumn,";
            strSql += "OverYearSpec,";
            strSql += "Remark)";
            strSql += " values(";
            strSql += "@Id,";
            strSql += "@ReportId,";
            strSql += "@SeedUnitName,";
            strSql += "@Varieties,";
            strSql += "@SeedProducSpring,";
            strSql += "@SeedProducSummer,";
            strSql += "@SeedProducAutumn,";
            strSql += "@OverYearSpec,";
            strSql += "@Remark)";
            using (var dbCon = ConnectFactory.GetOpenConnection())
            {
                var trans = dbCon.BeginTransaction();
                try
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        list[i].Id = CustomFun.GetGuid();
                    }

                    string strDel = "delete from dbo.T_MulEggsProducStatist where ReportId=@ReportId";
                    dbCon.Execute(strDel, new { ReportId = list[0].ReportId }, trans);
                    int result = dbCon.Execute(strSql, list, trans);
                    string strRep = "update dbo.T_Report set Status='2',UpdateTime=@UpdateTime where Id=@ReportId";
                    dbCon.Execute(strRep, new { ReportId = list[0].ReportId, UpdateTime = DateTime.Now }, trans);
                    //提交事务
                    trans.Commit();
                    obj.model = result;
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "更新成功！";
                    dbCon.Dispose();//数据库连接释放
                    return obj;

                }
                catch (Exception ex)
                {
                    obj.status = DefaultKey.ErrorResult;
                    obj.message = ex.ToString().Trim();
                    LogHelper.ErrorLog("新增表4全年饲养蚕品种构成调查表T_MulEggsProducStatist对象信息失败", ex);
                    return obj;
                }
            }
        }

        /// <summary>
        /// 读取导入的Excel数据
        /// </summary>
        /// <param name="pathName">导入文件路径</param>
        /// <param name="fileSuffix">文件后缀</param>
        /// <param name="sheetName">sheet名称</param>
        /// <param name="startRow">从第几行开始读取数据</param>
        /// <returns></returns>
        public List<MulEggsInfoModel> ExcelToModel(string pathName, string fileSuffix, string sheetName, int startRow)
        {

            IWorkbook workbook = null;
            ISheet sheet = null;
            List<MulEggsInfoModel> list = new List<MulEggsInfoModel>();
            FileStream fs = new FileStream(pathName, FileMode.Open, FileAccess.Read);
            switch (fileSuffix)
            {
                case ".xls":
                    workbook = new HSSFWorkbook(fs);
                    break;
                case ".xlsx":
                    workbook = new XSSFWorkbook(fs);
                    break;
                default:
                    workbook = new HSSFWorkbook(fs);
                    break;
            }
            if (!string.IsNullOrEmpty(sheetName))
            {
                sheet = workbook.GetSheet(sheetName);
                if (sheet == null) //如果没有找到指定的sheetName对应的sheet，则尝试获取第一个sheet
                {
                    sheet = workbook.GetSheetAt(0);
                }
            }
            else
            {
                sheet = workbook.GetSheetAt(0);
            }
            if (sheet != null)
            {
                //获取有数据的行数
                int rowCount = 0;
                for (int i = startRow; i <= sheet.LastRowNum; i++)
                {
                    IRow row = sheet.GetRow(i);
                    if (row != null)
                    {
                        rowCount = sheet.GetRow(i).RowNum;
                    }
                    else
                    {
                        break;
                    }
                }
                for (int i = startRow; i <= rowCount; i++)
                {
                    IRow row = sheet.GetRow(i);
                    MulEggsInfoModel model = new MulEggsInfoModel();
                    if (row.GetCell(0) != null && row.GetCell(0).ToString() != "")
                    {
                        model.SeedUnitName = row.GetCell(0).ToString();
                    }
                    else
                    {
                        model.SeedUnitName = null;
                    }
                    if (row.GetCell(1) != null && row.GetCell(1).ToString() != "")
                    {
                        model.Varieties = dict.GetPZKey(row.GetCell(1).ToString(), "CSCultivar");
                    }
                    else
                    {
                        model.Varieties = null;
                    }
                    if (row.GetCell(2) != null && row.GetCell(2).ToString() != "")
                    {
                        model.SeedProducSpring = decimal.Parse(row.GetCell(2).ToString());
                    }
                    else
                    {
                        model.SeedProducSpring = null;
                    }
                    if (row.GetCell(3) != null && row.GetCell(3).ToString() != "")
                    {
                        model.SeedProducSummer = decimal.Parse(row.GetCell(3).ToString());
                    }
                    else
                    {
                        model.SeedProducSummer = null;
                    }
                    if (row.GetCell(4) != null && row.GetCell(4).ToString() != "")
                    {
                        model.SeedProducAutumn = decimal.Parse(row.GetCell(4).ToString());
                    }
                    else
                    {
                        model.SeedProducAutumn = null;
                    }
                    if (row.GetCell(5) != null && row.GetCell(5).ToString() != "")
                    {
                        model.OverYearSpec = decimal.Parse(row.GetCell(5).ToString());
                    }
                    else
                    {
                        model.OverYearSpec = null;
                    }
                    if (row.GetCell(6) != null && row.GetCell(6).ToString() != "")
                    {
                        model.Remark = row.GetCell(6).ToString();
                    }
                    else
                    {
                        model.Remark = null;
                    }
                    list.Add(model);
                }
            }
            return list;
        }

        /// <summary>
        /// 添加
        /// </summary>
        public virtual ResResult<int> AddInfo(List<MulEggsInfoModel> model,string ReportId )
        {
            ResResult<int> obj = new ResResult<int>();
            string strSql = @"INSERT INTO dbo.T_MulEggsProducStatist";
            strSql += "(";
            strSql += "Id,";
            strSql += "ReportId,";
            strSql += "SeedUnitName,";
            strSql += "Varieties,";
            strSql += "SeedProducSpring,";
            strSql += "SeedProducSummer,";
            strSql += "SeedProducAutumn,";
            strSql += "OverYearSpec,";
            strSql += "Remark)";
            strSql += " values(";
            strSql += "@Id,";
            strSql += "@ReportId,";
            strSql += "@SeedUnitName,";
            strSql += "@Varieties,";
            strSql += "@SeedProducSpring,";
            strSql += "@SeedProducSummer,";
            strSql += "@SeedProducAutumn,";
            strSql += "@OverYearSpec,";
            strSql += "@Remark)";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    for(var i = 0; i < model.Count; i++)
                    {
                        model[i].Id = CustomFun.GetGuid();
                        model[i].ReportId = ReportId;
                    }
                   
                    int result = dbCon.Execute(strSql, model);
                    if (result > 0)
                    {
                        obj.model = result;
                        obj.status = DefaultKey.SuccessResult;
                        obj.message = "添加成功！";
                    }
                    else
                    {
                        obj.model = result;
                        obj.status = DefaultKey.InfoResult;
                        obj.message = "添加失败！数量为:" + result;
                    }
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("新增表5蚕种生产情况统计表T_MulEggsProducStatist对象信息失败", ex);
                return obj;
            }
        }
        /// <summary>
        /// 修改
        /// </summary>
        public virtual ResResult<int> UpdateInfo(MulEggsInfoModel model)
        {
            ResResult<int> obj = new ResResult<int>();
            string strSql = @"UPDATE dbo.T_MulEggsProducStatist set ";
            strSql += "SeedUnitName = @SeedUnitName,";
            strSql += "Varieties = @Varieties,";
            strSql += "SeedProducSpring = @SeedProducSpring,";
            strSql += "SeedProducSummer = @SeedProducSummer,";
            strSql += "SeedProducAutumn = @SeedProducAutumn,";
            strSql += "OverYearSpec = @OverYearSpec,";
            strSql += "Remark = @Remark";
            strSql += " where ReportId = @ReportId";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    int result = dbCon.Execute(strSql, model);
                    if (result > 0)
                    {
                        obj.model = result;
                        obj.status = DefaultKey.SuccessResult;
                        obj.message = "更新成功！";
                    }
                    else
                    {
                        obj.model = result;
                        obj.status = DefaultKey.InfoResult;
                        obj.message = "更新失败！数量为:" + result;
                    }
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("更新表5蚕种生产情况统计表T_MulEggsProducStatist对象信息失败", ex);
                return obj;
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        public ResResult<int> DeleteData(string id)
        {
            ResResult<int> obj = new ResResult<int>();
            string strSql = @"delete from dbo.T_MulEggsProducStatist where ReportId = @Id";
            int result;
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    result = dbCon.Execute(strSql, new { Id = id });
                    if (result > 0)
                    {
                        obj.model = result;
                        obj.status = DefaultKey.SuccessResult;
                        obj.message = "删除成功！";
                    }
                    else
                    {
                        obj.model = result;
                        obj.status = DefaultKey.InfoResult;
                        obj.message = "删除失败！数量为:" + result;
                    }
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("删除表5蚕种生产情况统计表T_MulEggsProducStatist对象信息失败", ex);
                return obj;
            }
        }
        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public MemoryStream Method(MulNowModel model)
        {
            ReportServices reportServices = new ReportServices();
            model.FillInYear = dict.GetKey(model.FillInYear);
            string ReportId = reportServices.GetReportId(model.ReportCode, model.AreaCode, model.FillInYear);
            FileStream file = null;
            //创建下载Excel文件
            var workbook = new HSSFWorkbook();
            string fileIndex = HttpRuntime.AppDomainAppPath.ToString();
            string filename = @"tempfile\Basic" + DateTime.Now.Ticks.ToString() + ".xls";//临时文件，定期在tempfile手动删除
            string tempExcel = fileIndex + filename;//临时文件路径及全称
            string templateName = fileIndex + @"Excel\Excel.xls";//模板文件
            file = new FileStream(templateName, FileMode.Open, FileAccess.Read);//读模板文件
            HSSFWorkbook templateBook = new HSSFWorkbook(file);//读取模板文件信息转换成Excel工作薄
            HSSFSheet sheet = templateBook.GetSheet("MulEggsProducStatist") as HSSFSheet;//读取模板所在sheet位置
            List<MulEggsProducStatistEntity> pagelist = GetList(ReportId).model;//数据获取

            HSSFRow row = (HSSFRow)sheet.GetRow(1);//读取模板第二行
            var style = row.GetCell(0).CellStyle;//读取模板第二行第一单元格样式并保存
            row.GetCell(0).CellStyle = style;//对第二行第一单元格设置原来样式

            for (var i = 0; i < pagelist.Count; i++)
            {
                HSSFRow datarow = (HSSFRow)sheet.CreateRow(i + 3);
                var Total = pagelist[i].SeedProducSpring + pagelist[i].SeedProducSummer + pagelist[i].SeedProducAutumn;
                datarow.CreateCell(0).SetCellValue(pagelist[i].SeedUnitName == null ? "" : pagelist[i].SeedUnitName.ToString());
                datarow.CreateCell(1).SetCellValue(pagelist[i].Varieties == null ? "" : dict.GetPZName(pagelist[i].Varieties, "CSCultivar"));
                datarow.CreateCell(2).SetCellValue(Convert.ToDouble(Total));
                datarow.CreateCell(3).SetCellValue(pagelist[i].SeedProducSpring == null ? "" : pagelist[i].SeedProducSpring.ToString());
                datarow.CreateCell(4).SetCellValue(pagelist[i].SeedProducSummer == null ? "" : pagelist[i].SeedProducSummer.ToString());
                datarow.CreateCell(5).SetCellValue(pagelist[i].SeedProducAutumn == null ? "" : pagelist[i].SeedProducAutumn.ToString());
                datarow.CreateCell(6).SetCellValue(pagelist[i].OverYearSpec == null ? "" : pagelist[i].OverYearSpec.ToString());
                datarow.CreateCell(7).SetCellValue(pagelist[i].Remark == null ? "" : pagelist[i].Remark.ToString());
                for(int j=0;j<8;j++)
                {
                    datarow.GetCell(j).CellStyle = style;
                }
            }
            sheet.CopyTo(workbook, "Sheet1", true, true);
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
                return ms;
            }
        }
        /// <summary>
        ///  全年蚕种生产情况--------(按年度统计)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResResult<List<MulEggsStatsModel>> GetMulEggsProducStatsList(MulNowModel model)
        {
            ResResult<List<MulEggsStatsModel>> result = new ResResult<List<MulEggsStatsModel>>();
            DictServices dictServices = new DictServices();
            if (!string.IsNullOrEmpty(model.FillInYear))
            {
                model.FillInYear = dictServices.GetPZKey(model.FillInYear, "ReportYear");
            }
            //统计代码
            string StrSql = "select case when grouping(SeedUnitName) is NULL then '合计' else SeedUnitName end SeedUnitName, ";
            //StrSql += "Varieties Varieties,";
            StrSql += "SUM(SeedProducSpring) AS SeedProducSpring,";
            StrSql += "SUM(SeedProducSummer) AS SeedProducSummer,";
            StrSql += "SUM(SeedProducAutumn) AS SeedProducAutumn,";
            StrSql += "SUM(OverYearSpec) AS OverYearSpec from ";
            StrSql += "(select  DictText FillYear ,SeedUnitName,Varieties,ISNULL(SeedProducSpring, 0.00) SeedProducSpring,  ";
            StrSql += "ISNULL(SeedProducSummer, 0.00) SeedProducSummer,ISNULL(SeedProducAutumn, 0.00) SeedProducAutumn,  ";
            StrSql += "OverYearSpec,MulEggs.Remark  from T_Report Report inner join  T_MulEggsProducStatist MulEggs  on Report.Id = MulEggs.ReportId  ";
            if (model.itemText != "" && model.itemText != null)
            {
                StrSql += " and Varieties=@itemText ";
            }
            StrSql += "left join T_Dict Dict  on Report.FillInYear = Dict.DictValue and GroupCode = 'ReportYear'   ";
            StrSql += "left join T_Area Area on Report.AreaCode = Area.Code where Report.FillInYear =@FillInYear and Report.Status=@ReportStatus ";
            if (model.AreaCode != DefaultKey.ProvinceCode) {
                StrSql += "and Area.ParentCode=@AreaCode ";
            }
            StrSql += ")t group by rollup(SeedUnitName) ";
            StrSql += "order by SeedProducSpring desc,SeedProducAutumn desc,SeedProducSummer desc,OverYearSpec desc ";
            
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    var paramlist = new DynamicParameters();
                    paramlist.Add("AreaCode", model.AreaCode);
                    paramlist.Add("FillInYear", model.FillInYear);
                    paramlist.Add("ReportStatus", model.Status);
                    paramlist.Add("itemText", model.itemText);//品种
                    List<MulEggsStatsModel> list = new List<MulEggsStatsModel>();
                    List<MulEggsStatsModel> list1 = new List<MulEggsStatsModel>();
                    list = dbCon.Query<MulEggsStatsModel>(StrSql, paramlist).ToList();
                    foreach (var mulegg in list)
                    {
                        //mulegg.Varieties = dictServices.GetPZName(mulegg.Varieties, "CSCultivar");
                        mulegg.SeedProducTotal = mulegg.SeedProducSpring + mulegg.SeedProducSummer + mulegg.SeedProducAutumn;
                        if (mulegg.FillYear == null)
                        {
                            mulegg.FillYear = dict.GetPZName(model.FillInYear, "ReportYear");
                        }
                        list1.Add(mulegg);
                    }
                    //List<MulEggsStatsModel> list2 = new List<MulEggsStatsModel>();
                    //MulEggsStatsModel m = new MulEggsStatsModel();
                    //if (list1.Count!=0) {
                    //    //m.AreaName = "合计";
                    //    m.FillYear = list1[0].FillYear + "合计";
                    //    //m.SeedUnitName = list1.Where(s => s.SeedUnitName != null).Count().ToString();
                    //    m.SeedUnitName = list1.Count().ToString();
                    //    m.SeedProducSpring = list1.Sum(s => s.SeedProducSpring);
                    //    m.SeedProducSummer = list1.Sum(s => s.SeedProducSummer);
                    //    m.SeedProducAutumn = list1.Sum(s => s.SeedProducAutumn);
                    //    m.SeedProducTotal = list1.Sum(s => s.SeedProducTotal);
                    //    m.OverYearSpec = list1.Sum(s => s.OverYearSpec);
                    //    list2.Add(m);
                    //    foreach (var item in list1)
                    //    {
                    //        list2.Add(item);
                    //    }
                    //}
                    //if (list2.Count==0) {
                    //    MulEggsStatsModel m2 = new MulEggsStatsModel();
                    //    m2.FillYear = dict.GetPZName(model.FillInYear, "ReportYear") + "合计";
                    //    m2.SeedUnitName = "0";
                    //    m2.SeedProducSpring = 0;
                    //    m2.SeedProducSummer = 0;
                    //    m2.SeedProducAutumn = 0;
                    //    m2.SeedProducTotal = 0;
                    //    m2.OverYearSpec = 0;
                    //    list2.Add(m2);
                    //}
                    if (list1 != null)
                    {
                        result.model = list1;
                        result.status = DefaultKey.SuccessResult;
                        result.message = "获取全年蚕种生产情况统计数据成功！";
                    }
                    else
                    {
                        result.status = DefaultKey.InfoResult;
                        result.message = "获取全年蚕种生产情况统计数据为空！";
                    }
                    dbCon.Dispose();//数据库连接释放
                }
            }
            catch (Exception ex)
            {
                result.status = DefaultKey.ErrorResult;
                result.message = ex.ToString().Trim();
                LogHelper.ErrorLog("获取全年蚕种生产情况统计数据失败", ex);
            }
            return result;
        }
        /// <summary>
        /// 导出统计数据
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public MemoryStream MethodStats(List<MulEggsStatsModel> list)
        {
            FileStream file = null;
            //创建下载Excel文件
            var workbook = new HSSFWorkbook();
            string fileIndex = HttpRuntime.AppDomainAppPath.ToString();
            string filename = @"tempfile\Basic" + DateTime.Now.Ticks.ToString() + ".xls";//临时文件，定期在tempfile手动删除
            string tempExcel = fileIndex + filename;//临时文件路径及全称
            string templateName = fileIndex + @"Excel\ExcelStats.xls";//模板文件
            file = new FileStream(templateName, FileMode.Open, FileAccess.Read);//读模板文件
            HSSFWorkbook templateBook = new HSSFWorkbook(file);//读取模板文件信息转换成Excel工作薄
            HSSFSheet sheet = templateBook.GetSheet("MulEggsProducStatist") as HSSFSheet;//读取模板所在sheet位置
            HSSFRow row = (HSSFRow)sheet.GetRow(1);//读取模板第二行
            var style = row.GetCell(0).CellStyle;//读取模板第二行第一单元格样式并保存
            var styleAreaInt = Common.GetIntAreaCellStyle(templateBook, style);
            if (list.Count > 0)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    HSSFRow datarow = (HSSFRow)sheet.CreateRow(i + 3);
                    //datarow.CreateCell(0).SetCellValue(list[i].FillYear == null ? "" : list[i].FillYear.ToString());
                    datarow.CreateCell(0).SetCellValue(list[i].SeedUnitName == null ? "" : list[i].SeedUnitName.ToString());
                    datarow.CreateCell(1).SetCellValue(list[i].Varieties == null ? "" : list[i].Varieties.ToString());
                    datarow.CreateCell(2).SetCellValue(list[i].SeedProducTotal == null ? 0 : Convert.ToDouble(list[i].SeedProducTotal));
                    datarow.CreateCell(3).SetCellValue(list[i].SeedProducSpring == null ? 0 : Convert.ToDouble(list[i].SeedProducSpring));
                    datarow.CreateCell(4).SetCellValue(list[i].SeedProducSummer == null ? 0 : Convert.ToDouble(list[i].SeedProducSummer));
                    datarow.CreateCell(5).SetCellValue(list[i].SeedProducAutumn == null ? 0 : Convert.ToDouble(list[i].SeedProducAutumn));
                    datarow.CreateCell(6).SetCellValue(list[i].OverYearSpec == null ? 0 : Convert.ToDouble(list[i].OverYearSpec));
                    datarow.CreateCell(7).SetCellValue(list[i].Remark == null ? "" : list[i].Remark.ToString());
                    for (var j = 0; j < 8; j++)
                    {
                        datarow.GetCell(j).CellStyle = styleAreaInt;
                    }
                }
            }
            sheet.CopyTo(workbook, "Sheet1", true, true);
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
                return ms;
            }
        }
    }
}